var camera = document.getElementById('camera');
var gallery = document.getElementById('gallery');

var isPlusReady = false;

document.addEventListener("plusready", function() {
	isPlusReady = true;
}, false);

// 加载状态
function LoadingMask(){
	this.el = mui('.progress')[0];
	this.mask = mui('.mask')[0];
	
	// 打开加载状态
	this.show = function(){
		this.mask.style.display = 'block';
		this.el.style.display = 'block';
		localStorage.setItem('loading', 1);
	}
	// 清除状态
	this.close = function(){
		this.mask.style.display = 'none';
		this.el.style.display = 'none';
		localStorage.setItem('loading', 0);
	}
	// 设置文字 
	this.setText = function(param){
		mui('.progress .text')[0].innerText = param;
	}
}
var loadingMaskInstance = new LoadingMask();
// 测试加载动画
//loadingMaskInstance.show();
//function close(){
//	loadingMaskInstance.close();
//}
//setTimeout(close, 1000);

// 如果手机过慢，导致点击时，plusReady事件没有触发，
// 则弹出提示框，500ms之后再次检测plusReady
function detectPlusReady(cb){
	if(env.isLoading()){
		loadingMaskInstance.show();
		loadingMaskInstance.setText('请稍后...')
	}
	if(cb && typeof(cb) == 'function'){
		if(isPlusReady) {
			loadingMaskInstance.close();
			cb();
		} else {
			setTimeout(detectPlusReady.bind(this,cb), 500);
		}
	} else {
		alert('detectPlusReady函数的参数必须是函数！');
	}
}

// 监听拍照按钮的点击事件
camera.addEventListener('tap', function() {
	detectPlusReady(captureImage);
})
// 调用摄像头拍照
function captureImage() {
	var cmr = plus.camera.getCamera();
	var res = cmr.supportedImageResolutions[0];
	var fmt = cmr.supportedImageFormats[0];
	
	cmr.captureImage(function(path) {
//			alert("Capture image success: " + path);
			
			compressImage(path);
		},
		function(error) {
//			mui.alert("拍照失败: " + error.message, '提示');
			console.log(error.message);
		}, {
			resolution: res,
			format: fmt
		}
	);
}
// 监听从相册选的按钮事件
gallery.addEventListener('tap', function(){
	detectPlusReady(pickImage);
})

// 选择图片
function pickImage(){
	plus.gallery.pick( function(path){
    	console.log(path);
		compressImage(path, true);
    }, function ( e ) {
    	console.log( "取消选择图片" );
    }, {filter:"image"} );
}
// 压缩照片，压缩完成后删除原照片，节省空间
function compressImage(src, isKeepSrc) {
	loadingMaskInstance.show();
	loadingMaskInstance.setText('提交中...');
	var ext = src.match(/\.(\w+)$/);
	var dist = '_downloads/' + (new Date()).getTime() + ext[0];
	plus.zip.compressImage({
		src: src,
		dst: dist,
		quality: 20 // 压缩质量
	},
	function() {
		if(!isKeepSrc){
			plus.io.resolveLocalFileSystemURL(src, function(entry) {
				entry.remove(function() {
					//alert(0);
				}, function() {
					//alert(1);
				});
			})
		}
		plus.gallery.save(dist);
		plus.io.resolveLocalFileSystemURL(dist, function(entry) {
			localStorage.setItem('imgUrl', entry.toLocalURL());
		})
		uploadImage(dist);
	},
	function(error) {
		mui.alert('提示', '识别失败！');
		return;
	});
}

// 上传图片
function uploadImage(path){
	var task = plus.uploader.createUpload(PORT_URL, {
		method: METHOD
	}, function(t, status) {
		// 上传完成
		loadingMaskInstance.close();
		if(status == 200) {
//			alert("Upload success: " + JSON.stringify(t));
			afterUploadSuccess(t.responseText);
		} else {
			mui.alert(status, '提示');
		}
	});
	task.addFile(path, {key:KEY_NAME});
	task.addData(TOKEN_NAME, TOKEN_VALUE);
	task.addEventListener( "statechanged", onStateChanged, false );
	task.start();
}
// 监听上传状态
function onStateChanged( upload, status ) {
	if(upload.state == 3){
//		console.log(upload.uploadedSize);
		var progress = Math.round((upload.uploadedSize / upload.totalSize) * 100) + '%';
		loadingMaskInstance.setText(progress);
	}
}

// 图片上传成功后处理函数
function afterUploadSuccess(responseText){
	mui.openWindow({
		url: '../html/detail.html',
		id: 'detail',
		extras: {
			responseText: responseText
		}
	})
}
